<template>
  <div>
    <van-nav-bar title="登录" />
    <!--  表单结构 -->
    <van-form @submit="logins">
      <van-field
        required
        v-model="mobile"
        label="手机号"
        placeholder="请输入你的手机号"
        :rules="rules.mobile"
      />
      <van-field
        required
        v-model="code"
        label="验证码"
        placeholder="请输入验证码"
        :rules="rules.code"
      />
      <div style="margin: 16px">
        <van-button
          round
          block
          type="info"
          native-type="submit"
          :disabled="isLoading"
          :loading="isLoading"
          loading-text="登录中..."
        >
          登录
        </van-button>
      </div>
    </van-form>
  </div>
</template>
<script>
import { userlogin } from '@/api/user'
import { mapMutations } from 'vuex'
export default {
  name: 'Login',
  data() {
    return {
      mobile: 17812345678,
      code: 246810,
      isLoading: false,
      rules: {
        // 校验手机号
        mobile: [
          {
            required: true,
            message: '手机号不能为空'
          },
          {
            pattern: /^1[3-9]\d{9}$/,
            message: '手机号码格式错误'
          }
        ],
        // 校验短信
        code: [
          {
            required: true,
            message: '验证码不能为空'
          },
          {
            pattern: /^\d{6}$/,
            message: '验证码格式错误'
          }
        ]
      }
    }
  },
  methods: {
    ...mapMutations('user', ['setToken']),
    async logins() {
      this.isLoading = true
      // 不能给提交按钮注册click来发送请求 ==> 因为表单校验不通过的时候，也会触发
      // 正确做法：
      // console.log('登录中....')
      try {
        const res = await userlogin(this.mobile, this.code)
        // console.log(res.data)
        // 存储token
        this.setToken(res.data)
        this.$toast.success('登录成功')
        // 登录成功跳转首页
        this.$router.push('/user')
      } catch (e) {
        this.$toast.fail('登录失败')
      }
      this.isLoading = false
    }
  }
}
</script>

<style lang="less" scoped></style>
